www.gusucode.com > PHP条码扫描管理系统 v1.0PHP源码程序 > PHP条码扫描管理系统 v1.0/wltmglxt_v1.0/wltmglxt_v1.0/upload/protected/controllers/IndexController.php

    <?php

class IndexController extends Controller
{
    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
  /*          array('allow',  // allow all users to access 'index' and 'view' actions.
                'actions'=>array('index','view'),
                'users'=>array('*'),
            ),*/
            array('allow', // allow authenticated users to access all actions
                'users'=>array('@'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
        $model=new Package;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Package']))
        {
            $model->uid = Yii::app()->user->id;
            $model->created = date('Y-m-d H:i:s',time());
            $model->attributes=$_POST['Package'];
            if($model->save()) {
                echo CJSON::encode(array(
                    'success'=>true,
                    'msg'=> '保存成功',
                    'url'=>$this->createUrl('index')
                ));
            } else {
                echo CJSON::encode(array(
                    'success'=>false,
                    'msg'=> '保存失败',
                    'url'=>$this->createUrl('index')
                ));
            }
        } else {
            $uid = Yii::app()->user->id;
            $criteria = new CDbCriteria;
            if (intval($uid) !=1) {
                $criteria->condition = "uid=$uid";
            }
            $criteria->order = 'created DESC';
            $count = Package::model()->count($criteria);
            $pages = new CPagination($count);
            $pages->pageSize = 10;
            $pages->applyLimit($criteria);
            $result = Package::model()->findAll($criteria);
            $this->render('index',array(
                'result' => $result,
                'pages'=> $pages,
                'model'=>$model,
            ));
        }
	}

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Package']))
        {
            $model->attributes=$_POST['Package'];
            if( $model->save() ) {
                $this->redirect(array('index'));
            }

        }

        $this->renderPartial('update',array(
            'model'=>$model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if (Yii::app()->user->id === $this->loadModel($id)->uid ) {
            $this->loadModel($id)->delete();
        }

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if(!isset($_GET['ajax'])) {
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
        }
    }

    /**
     * 生成excel文件
     */
    public function actionCreateExcel()
    {
        if ($_POST['Datetime']) {
            //生成文件名
            $filename = date('YmdHis');

            //查询数据库
            $criteria = new CDbCriteria;
            $criteria->addBetweenCondition('created', $_POST['Datetime']['begin'], $_POST['Datetime']['end']);
            $criteria->order = 'created DESC';
            $result = Package::model()->findAll($criteria);

            //生成Excel
            $objPHPExcel= XPHPExcel::createPHPExcel();
            $objPHPExcel->getProperties()->setCreator("www.focalhot.com")
                ->setLastModifiedBy("Warren Xia")
                ->setTitle("Office 2007 XLSX Test Document")
                ->setSubject("Office 2007 XLSX Test Document")
                ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                ->setKeywords("office 2007 openxml php")
                ->setCategory("Test result file");

            // Add some data
            foreach ($result as $k=>$v) {
                $k = $k + 1; //数组下标是从0开始,而excel中行和列是从1开始,所以输出A0和B0会忽略
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A'.$k, $v['weight'])
                    ->setCellValue('B'.$k, $v['tracking_no']);
            }

            // Rename worksheet
            $objPHPExcel->getActiveSheet()->setTitle('www.focalhot.com');

            // Set active sheet index to the first sheet, so Excel opens this as the first sheet
            $objPHPExcel->setActiveSheetIndex(0);

            // Redirect output to a client’s web browser (Excel5)
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
            header('Cache-Control: max-age=0');
            // If you're serving to IE 9, then the following may be needed
            header('Cache-Control: max-age=1');

            // If you're serving to IE over SSL, then the following may be needed
            header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
            header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header ('Pragma: public'); // HTTP/1.0

            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
            Yii::app()->end();
        }
    }
	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
				$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
				$headers="From: $name <{$model->email}>\r\n".
					"Reply-To: {$model->email}\r\n".
					"MIME-Version: 1.0\r\n".
					"Content-Type: text/plain; charset=UTF-8";

				mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return Package the loaded model
     * @throws CHttpException
     */
    public function loadModel($id)
    {
        $model=Package::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }
}